/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jeff.springWebTestNG.persistence.service;

import com.jeff.springWebTestNG.util.LogUtil;
import com.mongodb.*;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.stereotype.Component;

/**
 *
 * @author Jeff
 */
@Component
public abstract class BaseMongoPersister implements IBaseMongoPersister {
    static final Logger LOG = LogUtil.getLogger(BaseMongoPersister.class);
    DB db;
    protected DBCollection defaultColl;//any subType must instantiate this field individually
    

    public BaseMongoPersister() {
        try {
            Mongo m = new Mongo();
            db = m.getDB("mydb");
        } catch (UnknownHostException ex) {
            LOG.log(Level.SEVERE, null, ex);
        } catch (MongoException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void truncateColl() {
        defaultColl.drop();
    }
    
    @Override
    public DBCursor getCursor4All() {
        return defaultColl.find();
    }
    
    @Override
    public List<BasicDBObject> getAll() {
        List<BasicDBObject> ret = new ArrayList<BasicDBObject>();
        DBCursor cursor = defaultColl.find();
        while(cursor.hasNext()) {
            ret.add((BasicDBObject) cursor.next());
        }
        
        return ret;
    }
    
    @Override
    public List<DBObject> getByCond(DBObject query) {
        List<DBObject> ret = collectListByCursor(defaultColl.find(query));
        
        return ret;
    }
            
    protected List<DBObject> collectListByCursor(DBCursor cursor) {
        List<DBObject> ret = new ArrayList<DBObject>();
        
        while(cursor.hasNext()) {
            ret.add((DBObject) cursor.next());
        }
        
        return ret;
    }
}
